package thread;

import java.util.PriorityQueue;

class MyTimerTask4 implements Comparable<MyTimerTask4>{
    private long time;
    private Runnable runnable;

    public long getTime(){
        return time;
    }
    public void run(){
        runnable.run();
    }
    public MyTimerTask4(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }
    @Override
    public int compareTo(MyTimerTask4 o) {
        return (int) (this.time - o.time);
    }
}
class MyTimer4{
    private Object locker = new Object();
    private Thread t = null;
    private  PriorityQueue<MyTimerTask4> queue = new PriorityQueue<>();
    public MyTimer4(){
        t = new Thread(() ->{
            while(true){
                synchronized (locker){
                    try {
                        while(queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask4 task4 = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if(curTime >= task4.getTime()){
                            queue.poll();
                            task4.run();
                        } else {
                            locker.wait(task4.getTime() - curTime);
                        }
                    } catch(InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }
    public void schedule(Runnable runnable, long time){
        synchronized (locker){
            MyTimerTask4 task4 = new MyTimerTask4(runnable,time);
            queue.offer(task4);
            locker.notify();
        }
    }
}



public class ThreadDemo34 {
    public static void main(String[] args) {
        MyTimer4 timer4 = new MyTimer4();
        timer4.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
        timer4.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);
        timer4.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
        System.out.println("hello main");
    }
}
